<?php
Yii::import('zii.widgets.grid.CDataColumn', true);

class GridDataColumn extends CDataColumn
{
	/**
	 * @var string a PHP expression that will be evaluated as link url
	 */
	public $url;
	public $linkOptions = array();

	/**
	 * @var int the maxmum length of data cell content
	 */
	public $maxLength = 0;

	protected function renderDataCellContent($row, $data)
	{
		$value = null;
		$options = array();
		if ($this->value !== null) {
			$value = $this->evaluateExpression($this->value, array('data' => $data, 'row' => $row));
		} elseif ($this->name !== null) {
			$value = CHtml::value($data, $this->name);
		}
		if ($value === null) {
			$value = $this->grid->nullDisplay;
		} else {
			if ($this->maxLength > 0 && strlen($value) > $this->maxLength) {
				$options['title'] = $value;
				$value = self::cutValue($value, $this->maxLength);
			}
			$value = $this->grid->getFormatter()->format($value, $this->type);
		}
		if ($this->url !== null) {
			$url = $this->evaluateExpression($this->url, array('data' => $data, 'row' => $row));
			echo CHtml::link($value, $url, array_merge($this->linkOptions, $options));
		} elseif (count($options) > 0) {
			echo CHtml::tag('span', $options, $value);
		} else {
			echo $value;
		}
	}

	private static function cutValue($value, $end)
	{
		if (strlen($value) > $end) {
			while ((ord($value[$end]) & 0xc0) === 0x80) {
				$end--;
			}
			$value = substr($value, 0, $end) . '...';
		}
		return $value;
	}
}
